from mg_app_framework import (IdiServerConfigBasic, InitFuncBasic, app_start,
                              set_config_func, set_init_task, set_store, rabbitmq_get_subscribe_message_cache,
                              get_logger, update_context, get_organization, get_context)
from mg_app_framework.components import TaskKey

from common.basic_mongo import get_mongo_collection
from service_log_viewer.servce_constant import DB_ACCESS_LOG_CONFIG
from service_log_viewer.service_log_rabbitmq import RabbitMQConfig, process_mq_msg
from service_log_viewer.config import ConfigStore, RedisConfigBasic


async def config_process():
    pass


class InitFuncConfig(InitFuncBasic):
    async def init_func(self):
        await self.deal_mq_message_catch()
        await self.init_context()

    @classmethod
    async def init_context(cls):
        access_log_config_handler = get_mongo_collection(
            collection_name=DB_ACCESS_LOG_CONFIG,
            database_name=f"idi_{get_organization()}_upper_pc",
        )
        access_log_configs = access_log_config_handler.find({}, {"_id": 0})
        api_string_select = get_context("api_string_select")
        api_string_mapper = get_context("api_string_mapper")
        async for item in access_log_configs:
            url = item["url"]
            url_name = item["url_name"]
            api_string_select.append({
                "label": url_name,
                "prop": url
            })
            api_string_mapper[url] = url_name

    @classmethod
    async def deal_mq_message_catch(cls):
        try:
            # 处理缓存配置MQ信息
            cached_mq_message = await rabbitmq_get_subscribe_message_cache()
            current_orgs = set()
            if cached_mq_message:
                for key, value in cached_mq_message.items():
                    if '~' in key:
                        msg_org, msg_key = key.split('~')
                        current_orgs.add(msg_org)
                        await process_mq_msg({'key': msg_key, 'data': value, 'organization': msg_org})
                    else:
                        await process_mq_msg({'key': key, 'data': value})
        except Exception as e:
            get_logger().error("deal_mq_message_catch error:{}".format(e))


def main(debug_flag=True):
    set_store(ConfigStore())
    set_config_func(config_process)
    update_context("user_code_dict", {})
    update_context("user_code_select_list", [])
    update_context("api_string_select", [])
    update_context("api_string_mapper", {})
    update_context("process_code_select", [])
    update_context("device_code_mapper", {})
    update_context("process_code_mapper", {})

    set_init_task(
        [
            # {TaskKey.redis_async: RedisConfigBasic()},
            {TaskKey.idi_server: IdiServerConfigBasic()},
            {TaskKey.rabbitmq_async: RabbitMQConfig()},
            {TaskKey.init_func: InitFuncConfig()},
        ]
    )
    app_start(debug_flag)
